package jdk.lambda.collectors;

import jdk.entity.UserEntity;
import jdk.entity.UserEntityList;

import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;

/**
 * Copyright (C), 2022, szw
 * FileName: GroupingByTest
 *
 * @author songyafei
 * Date:     2022/1/17 14:13
 * Description: 分组案例
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
public class GroupingByTest {

    public static void main(String[] args) {
        List<UserEntity> item = UserEntityList.getItem();
        List<UserEntity> s = item.parallelStream().sorted(Comparator.comparing(UserEntity::getAge)).collect(Collectors.toList());
        /**
         * 场景1： 根据日期分组
         */
        Map<LocalDate, List<UserEntity>> m1 = s.stream().collect(Collectors.groupingBy(UserEntity::getCreatedDate));
        /**
         * 场景2 ： 根据日期分组获取所有名字
         */
        Map<LocalDate, List<String>> m2 = s.stream().collect(Collectors.groupingBy(UserEntity::getCreatedDate, Collectors.mapping(m -> m.getName(), Collectors.toList())));
        /**
         * 场景3： 保证顺序性（按照集合已经排的序）根据日期分组
         */
        TreeMap<LocalDate, List<UserEntity>> m3 = s.stream().collect(Collectors.groupingBy(UserEntity::getCreatedDate, TreeMap::new, Collectors.toList()));


        //线程安全

        /**
         * 场景1： 根据报告期分组
         */
        ConcurrentMap<LocalDate, List<UserEntity>> c1 = s.stream().collect(Collectors.groupingByConcurrent(UserEntity::getCreatedDate));
        /**
         * 场景2 ： 根据日期分组获取所有名字
         */
        ConcurrentMap<LocalDate, List<UserEntity>> c2 = s.stream().collect(Collectors.groupingByConcurrent(UserEntity::getCreatedDate, Collectors.toList()));
        /**
         * 场景3： 保证顺序性（按照集合已经排的序）根据日期分组
         */
        ConcurrentSkipListMap<LocalDate, List<UserEntity>> c3 = s.stream().collect(Collectors.groupingByConcurrent(UserEntity::getCreatedDate, ConcurrentSkipListMap::new, Collectors.toList()));


        /**
         * 真实案例: 根据日期分组，并对value 只取年龄最小的 并且最终的map为treeMap
         */
        TreeMap<LocalDate, Optional<UserEntity>> z1 = s.stream().collect(
                Collectors.groupingBy(UserEntity::getCreatedDate, TreeMap::new,
                    Collectors.reducing(
                        BinaryOperator.minBy(
                                Comparator.comparing(UserEntity::getAge)))
        ));
        UserEntity userEntity = z1.get(LocalDate.of(2021, 1, 17)).orElse(new UserEntity(11L,12,"四",LocalDate.now()));
        System.out.println(userEntity.toString());

    }
}
